package cc.eddic.pratice.programmingparadigms.emp02list.impl;

import cc.eddic.pratice.programmingparadigms.Employee;
import cc.eddic.pratice.programmingparadigms.EmployeeComparator;
import cc.eddic.pratice.programmingparadigms.EmployeePredicate;
import cc.eddic.pratice.programmingparadigms.emp02list.EmployeeList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class EmployeeListTyqImpl implements EmployeeList {

    private static final Logger log = LoggerFactory.getLogger(EmployeeListTyqImpl.class);
    Employee[] employees;
    int index = -1;

    public EmployeeListTyqImpl(int capacity) {
        employees = new Employee[capacity];
    }

    @Override
    public void add(Employee employee) {
        if (size() == employees.length) {
            if (log.isDebugEnabled()) {
                log.debug("上一个ResultList已满，长度为：{}，正在扩容。。。", size());
            }
            EmployeeListTyqImpl newEmployee = new EmployeeListTyqImpl(size() * 2);
            for (Employee employee1 : employees) {
                newEmployee.add(employee1);
            }
            newEmployee.add(employee);
            index++;
            this.employees = newEmployee.employees;
            if (log.isDebugEnabled()) {
                log.debug("扩容成功，扩容后当前长度为：{}", size());
            }
        } else {
            employees[size()] = employee;
            index++;
        }
    }

    @Override
    public Employee get(int index) {
        if (index > size() - 1) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
        }
        return employees[index];
    }

    @Override
    public int size() {
        return index + 1;
    }

    @Override
    public Employee find(EmployeePredicate predicate) {
        for (int i = 0; i < size(); ++i) {
            Employee r = get(i);
            if (predicate.test(r)) {
                return r;
            }
        }
        return null;
    }

    @Override
    public void sort(EmployeeComparator comparator) {
        // 冒泡排序
        for (int i = 0; i < size(); i++) {
            for (int j = 0; j < size() - i - 1; j++) {
                // 什么情况下要交换
                if (comparator.compare(employees[j], employees[j + 1]) > 0) {
                    // 交换
                    Employee temp = employees[j];
                    employees[j] = employees[j + 1];
                    employees[j + 1] = temp;
                }
            }
        }
    }
}
